﻿using Aliyun.OSS;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Wq.Extensions.Common
{
    /// <summary>
    /// 阿里云oss操作类
    /// </summary>
    public class AliyunOSSHelper
    {
        private static string accessKeyId = AppSettings.app("AliyunOss:AccessKeyId");
        private static string accessKeySecret = AppSettings.app("AliyunOss:AccessKeySecret");
        private static string endpoint = AppSettings.app("AliyunOss:Endpoint");
        private static string bucketName = AppSettings.app("AliyunOss:BucketName");
        static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="objectName"></param>
        /// <param name="fileStream"></param>
        /// <returns></returns>
        public static string PutObject(string objectName, Stream fileStream)
        {
            try
            {
                var result = client.PutObject(bucketName, objectName, fileStream);
                return result.ETag;
            }
            catch (Exception ex)
            {
                throw new MyException("上传失败" + JsonConvert.SerializeObject(ex));
            }

        }

        /// <summary>
        /// 获取内容
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="MyException"></exception>
        public static Stream GetObject(string key)
        {
            try
            {
                var result = client.GetObject(bucketName, key);
                return result.Content;
            }
            catch (Exception ex)
            {
                throw new MyException("获取失败" + JsonConvert.SerializeObject(ex));
            }
        }

        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsExist(string key) => client.DoesObjectExist(bucketName, key);

    }
}
